<template>
  <div class="box" ref="box">
    <div class="item" v-for="(item, index) in 100" :key="index">
      <img
        :data-src="`https://dummyimage.com/300x${getRandom(300, 500)}/${color16()}`"
        alt=""
        src="../../assets/imgs/test.jpg"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
const getRandom = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}
const color16 = () => {
  let r = Math.floor(Math.random() * 256)
  let g = Math.floor(Math.random() * 256)
  let b = Math.floor(Math.random() * 256)
  let color = r.toString(16) + g.toString(16) + b.toString(16)
  return color
}
const box = ref()
onMounted(() => {
  console.log(box.value)
  const ob = new IntersectionObserver(
    (entries) => {
      for (let item of entries) {
        if (item.isIntersecting) {
          item.target.src = item.target.dataset.src
          ob.unobserve(item.target)
        }
      }
    },
    {
      threshold: 0
    }
  )


  const imgs = document.querySelectorAll('img')
  imgs.forEach((item) => {
    ob.observe(item)
  })
})
</script>

<style lang="scss" scoped>
.box {
  column-count: 4;
  column-gap: 40px;
  width: 1200px;
  margin: auto;
}
</style>
